package com.bwie.service.impl;

import com.bwie.common.constants.Constants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Dict;
import com.bwie.common.domain.Literature;
import com.bwie.common.domain.request.LiteratureListReq;
import com.bwie.common.domain.response.LiteratureListResp;
import com.bwie.common.exceptions.LiteratureInfoExceptions;
import com.bwie.common.utils.StringUtils;
import com.bwie.domain.excel.ImportExcel;
import com.bwie.mapper.LiteratureMapper;
import com.bwie.service.LiteratureService;
import com.bwie.util.EasyPoiUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @className: LiteratureServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 李明
 * @date: 2025/11/10 10:32
 */
@Service
public class LiteratureServiceImpl implements LiteratureService {

    private static final String LITERATURE_INFO_DATA = "literature_info_data";
    @Autowired
    private LiteratureMapper literatureMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private EasyPoiUtil<ImportExcel> easyPoiUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;



    /**
     * 资源列表展示、分页无问题（3分）
     *
     * @param literatureListReq
     */
    @Override
    public List<LiteratureListResp> literatureList(LiteratureListReq literatureListReq) {
        List<LiteratureListResp> literatureListFormDB =
                literatureMapper.literatureList(literatureListReq);
        return literatureListFormDB;
    }

    /**
     * 上传文件
     *
     * @param multipartFile
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Literature> importLiteratureData(MultipartFile multipartFile) {
        List<ImportExcel> importExcels = easyPoiUtil.importFileExcel(multipartFile, ImportExcel.class);
        if (importExcels.size()<=0){
            throw new LiteratureInfoExceptions(Constants.LITERATURE_SIZE_ERROR_CODE,
                    Constants.LITERATURE_SIZE_ERROR_MSG);
        }

        //创建空集合
        ArrayList<Literature> literatureArrayList = new ArrayList<>();
        importExcels.forEach(importExcel -> {
            //对导入的数据进行校验
            String titleName = importExcel.getTitleName();

            //通过文件类型名称查询文件类型
            String literatureTypeName = importExcel.getLiteratureType();
            Integer literatureType = literatureMapper.getLiteratureTypeByName(literatureTypeName);

            //通过学科名称获取学科ID
            String literatureProjectName = importExcel.getLiteratureProject();
            Integer literatureProject = literatureMapper.getLiteratureProjectByName(literatureProjectName);

            //描述：参考（图1-3）数据导入到平台的需要数据校验，不符合的规则程序终止导入。
            //数据非空校验
            validateData(titleName, literatureTypeName, literatureProjectName);

            Literature literature = new Literature();
            BeanUtils.copyProperties(importExcel, literature);
            literature.setLiteratureType(literatureType);
            literature.setLiteratureProject(literatureProject);
            literatureArrayList.add(literature);

            //，并且提示用户
            rabbitTemplate.convertAndSend("literature_info", literature);

        });
        //将数据返回给前台
        return literatureArrayList;
    }


    /**
     * 数据非空校验
     * @param titleName
     * @param literatureTypeName
     * @param literatureProjectName
     */
    private void validateData(String titleName, String literatureTypeName, String literatureProjectName) {
        if (StringUtils.isBlank(titleName)){
            throw new LiteratureInfoExceptions(Constants.VALIDATE_DATE_CODE,
                    Constants.VALIDATE_DATE_MSG);
        }
        if (StringUtils.isBlank(literatureTypeName)){
            throw new LiteratureInfoExceptions(Constants.VALIDATE_DATE_CODE,
                    Constants.VALIDATE_DATE_MSG);
        }
        if (StringUtils.isBlank(literatureProjectName)){
            throw new LiteratureInfoExceptions(Constants.VALIDATE_DATE_CODE,
                    Constants.VALIDATE_DATE_MSG);
        }
    }

    /**
     * 下拉框
     *
     * @param dictType
     */
    @Override
    public List<Dict> selectDictValue(String dictType) {
        List<Dict> dictList = literatureMapper.selectDictValue(dictType);
        return dictList;
    }


    /**
     * 资源列表展示-查重 需要缓存当前数据
     */
    @Override
    public List<Literature> getLiteraturePage(LiteratureListReq literatureListReq) {
        try {
            //判断Redis中数据是否存在数据
            Boolean aBoolean = redisTemplate.hasKey(LITERATURE_INFO_DATA);
            //现从Redis中的获取数据
            if (aBoolean){
                List<Literature> literatureListFormRedis
                        = (List<Literature>) redisTemplate.opsForValue().get(LITERATURE_INFO_DATA);
                return literatureListFormRedis;
            }

            //若Redis中无数据时， 到数据库中获取数据
            List<Literature> literatureList = literatureMapper.literatureListFormBD(literatureListReq);

            //将数据库中的数据存入Redis中
            redisTemplate.opsForValue().set(LITERATURE_INFO_DATA, literatureList, 30, TimeUnit.MINUTES);

            //响应给前台
            return literatureList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
